#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>

int main(int argc,char **argv)
{
    int err;
    struct timespec tout;
    struct tm *tmp;
    char buf[64];
    pthread_mutex_t lock =  PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_lock(&lock);
    printf("mutex is locked\n");
    clock_gettime(CLOCK_REALTIME,&tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf,sizeof(buf),"%r",tmp);
    printf("current time is %s \n  ",buf);
    tout.tv_sec +=10;
    /**
     * 若再此处解锁，则后面会执行  err==0 这个条件下的打印输出。
     * 可以直观得看到加锁超时和成功加锁的区别。
    */
    //pthread_mutex_unlock(&lock);
    err = pthread_mutex_timedlock( &lock,&tout);
    clock_gettime(CLOCK_REALTIME,&tout);
    strftime(buf,sizeof(buf),"%r",tmp);
    printf("the time is now %s \n  ",buf);

    if( err== 0)
        printf("mutex locked again\n");
    else
        printf("can not lock mutex again, %s\n",strerror(err));
    exit(0);

}